// pages/read/read.js
import {
  getUserChannels,
  getChannelArtivles
} from '../../utils/api'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeTab: 0,
    userChannels: [],
    channelId: "" // 频道ID
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 用户选中的频道
    getUserChannels().then(res => {
      this.setData({
        userChannels: res.data.data.channels,
        channelId: res.data.data.channels[this.data.activeTab].id
      })
      // 给每个频道添加一个空文章数组
      res.data.data.channels.forEach(item => {
        item.articles = []
        item.no_more = false
      })
      // 获取第一个频道下的文章
      this.getAriticles(res.data.data.channels[0].id)
    })
  },
  // tab 切换
  onChannel(e) {
    let thisId = this.data.userChannels[e.detail.index].id
    this.data.activeTab = thisId
    // 如果该频道已有文章，则不获取 返回false
    if (this.data.userChannels[e.detail.index].articles[0]) return false
    // 获取频道下的文章
    this.getAriticles(thisId)
    // wx.pageScrollTo({
    //   scrollTop: 0,
    // })
    wx.pageScrollTo({
      duration: 300,
    })
  },
  // 获取频道下的文章
  getAriticles(thenId) {
    // 获取当前时间戳
    let stamp = (new Date().getTime()).toString()
    getChannelArtivles(thenId, stamp).then(res => {
      let theIndex = this.data.userChannels.findIndex(v => v.id == thenId)
      // 当获取到零篇文章时，给文章的no_more设置为true
      if (!res.data.data.results[0]) {
        let changeStr = 'userChannels[' + theIndex + '].no_more'
        this.setData({
          [changeStr]: true
        })
        return
      }
      // 给目标id的频道的 文章列表添加文章
      let changeStr = 'userChannels[' + theIndex + '].articles'
      this.data.userChannels[theIndex].articles = this.data.userChannels[theIndex].articles.concat(res.data.data.results)
      this.setData({
        [changeStr]: this.data.userChannels[theIndex].articles
      })
    })
  },
  // 触底刷新
  onReachBottom() {
    this.getAriticles(this.data.activeTab)    
  },
  // 跳转到文章详情页
  toArticle(e) {
    let aid = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/article/article?id=' + aid,
    })
  }
})